package com.dtsz.m2.ui.activity;

import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.android.volley.Request;
import com.dtsz.m2.R;
import com.dtsz.m2.config.StaticConfig;
import com.dtsz.m2.config.UrlConfig;
import com.dtsz.m2.ui.base.BaseActivity;
import com.dtsz.m2.ui.model.CertificationVo;
import com.dtsz.m2.ui.model.RegisterVo;
import com.dtsz.m2.utils.MyCountdownUtils;
import com.dtsz.m2.utils.StringUtils;
import com.dtsz.m2.volley.state.HUCState;

public class IdentificationCardActivity extends BaseActivity {
    //请求相机
    private static final int REQUEST_CAPTURE = 100;
    //请求相册
    private static final int REQUEST_PICK = 101;
    //请求截图
    private static final int REQUEST_CROP_PHOTO = 102;
    //请求访问外部存储
    private static final int READ_EXTERNAL_STORAGE_REQUEST_CODE = 103;
    //请求写入外部存储
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 104;

    private AlertDialog cerDialog;


    private EditText etName, etCard, etYhk, etPhone, etCode;

    private Button btLogin, btVerification;

    private CertificationVo certificationVo = new CertificationVo();

    private MyCountdownUtils myCountdownUtils;

    private RegisterVo registerVo = new RegisterVo();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_identification_card);
        super.onCreate(savedInstanceState);
        tvActionbarTitle.setText("实名认证");
        String name = getIntent().getExtras().getString("name");
        String card = getIntent().getExtras().getString("card");
        etName.setText(name);
        etCard.setText(card);
        getCertification();

    }


    @Override
    public void initView() {
        super.initView();
        etName = findViewById(R.id.et_name);
        etCard = findViewById(R.id.et_card);
        etPhone = findViewById(R.id.et_phone);
        etYhk = findViewById(R.id.et_yhk);
        etCode = findViewById(R.id.et_code);
        btLogin = findViewById(R.id.bt_login);
        btVerification = findViewById(R.id.bt_verification);
    }

    @Override
    public void initClick() {
        super.initClick();
        btLogin.setOnClickListener(this);
        btVerification.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_actionbar_left:
                finish();
                break;
            case R.id.bt_login:
                uploadInfo();
                break;
            case R.id.bt_verification:
                getCode();
                break;
        }
    }

    private void uploadInfo() {
        String card = etCard.getText().toString();
        if (!StringUtils.isIDNumber(card)) {
            showToast("身份证格式错误");
            return;
        } else {
            certificationVo.setBcCard(card);
        }
        String yhk = etYhk.getText().toString();
        if (!StringUtils.checkBankCard(yhk)) {
            showToast("银行卡格式错误");
            return;
        } else {
            certificationVo.setBcYhk(yhk);
        }
        String phone = etPhone.getText().toString();
        if (!StringUtils.isMobile(phone)) {
            Toast.makeText(this, "手机号码格式错误", Toast.LENGTH_LONG).show();
            return;
        } else {
            certificationVo.setBcPhone(phone);
        }
        String code = etCode.getText().toString();
        if (StringUtils.isEmpty(code)) {
            showToast("验证码不能为空");
            return;
        } else {
            certificationVo.setCode(code);
        }
        loading();
        certificationVo.setBcPhone(etPhone.getText().toString());
        certificationVo.setBcName(etName.getText().toString());
        certificationVo.setToken(pageVo.getToken());
        hucRequestInterfase.executeStr(this, String.class,
                HUCState.HUC_REQEUST_CODE_3, Request.Method.POST, UrlConfig.CERTIFICATION_URL,
                hucParameInterfase.getRequestParameter(certificationVo), true);

    }

    private void getCode() {
        String phone = etPhone.getText().toString();
        if (!StringUtils.isMobile(phone)) {
            Toast.makeText(this, "手机号码格式错误", Toast.LENGTH_LONG).show();
            return;
        } else {
            registerVo.setPhone(phone);
        }
        loading();
        registerVo.setToken(pageVo.getToken());
        registerVo.setType(StaticConfig.MSGCODE2);
        hucRequestInterfase.executeStr(this, RegisterVo.class,
                HUCState.HUC_REQEUST_CODE_1, Request.Method.POST, UrlConfig.CODE_URL,
                hucParameInterfase.getRequestParameter(registerVo), true);
    }

    private void getCertification() {
        hucRequestInterfase.executeStr(this, CertificationVo.class,
                HUCState.HUC_REQEUST_CODE_4, Request.Method.POST, UrlConfig.GETCERTIFICATION_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }


    ////////////////////////////////////////////////////////////////////
    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        super.onSuccessfulStrType(inputType, response);
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_3:
                String msg = (String) response;
                if ("验证码错误".equals(msg) || "验证码已过期".equals(msg) || msg.indexOf("此身份信息已被") != -1) {
                    showToast(msg);
                } else {
                    getDataName(msg);
                }
                break;
            case HUCState.HUC_REQEUST_CODE_4:
                if (response instanceof CertificationVo) {
                    CertificationVo certificationVo = (CertificationVo) response;
                    this.certificationVo = certificationVo;
                    pageVo.setId(certificationVo.getId());
                    String state = certificationVo.getBcState();
                    if ("0".equals(state)) {//审核中
                        btLogin.setText("审核中");
                        etCard.setText(certificationVo.getBcCard());
                        etYhk.setText(certificationVo.getBcYhk());
                        etPhone.setText(certificationVo.getBcPhone());
                        isIdent();
                    } else if ("-1".equals(state)) {//审核失败
                        isIdentif(certificationVo.getBcDescription());
                        etCard.setText(certificationVo.getBcCard());
                        etYhk.setText(certificationVo.getBcYhk());
                        etPhone.setText(certificationVo.getBcPhone());
                    }

                }

                break;
            case HUCState.HUC_REQEUST_CODE_5:
                finish();
                break;
            case HUCState.HUC_REQEUST_CODE_1:
                String reponseStr1 = (String) response;
                if ("验证码已发送，请注意查收".equals(reponseStr1)) {
                    myCountdownUtils = new MyCountdownUtils(btVerification, 60000, 1000);
                    myCountdownUtils.start();
                }
                showToast(reponseStr1);
                break;

        }
        loadDismiss();
    }

    AlertDialog alertDialog1;

    private void isIdent() {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        //dialog.setTitle("");
        dialog.setMessage("正在审核中");
        dialog.setPositiveButton("返回", null);

        alertDialog1 = dialog.create();
        alertDialog1.setCancelable(false);
        alertDialog1.show();

        //为了避免点击 positive 按钮后直接关闭 dialog,把点击事件拿出来设置
        alertDialog1.getButton(AlertDialog.BUTTON_POSITIVE)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //绑定用户v
                        finish();
                    }
                });
    }

    private void getDataName(String msg) {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        // dialog.setTitle("绑定姓名");
        dialog.setMessage(msg);
        dialog.setPositiveButton("确定", null);
        cerDialog = dialog.create();
        cerDialog.setCancelable(false);
        cerDialog.show();
        //为了避免点击 positive 按钮后直接关闭 dialog,把点击事件拿出来设置
        cerDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        cerDialog.dismiss();
                        finish();
                    }
                });
    }

    private void isIdentif(String content) {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("上次审核失败原因");
        dialog.setMessage(content);
        dialog.setPositiveButton("确定", null);
        alertDialog1 = dialog.create();
        alertDialog1.setCancelable(false);
        alertDialog1.show();

        //为了避免点击 positive 按钮后直接关闭 dialog,把点击事件拿出来设置
        alertDialog1.getButton(AlertDialog.BUTTON_POSITIVE)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //绑定用户v
                        alertDialog1.dismiss();
                    }
                });
    }


    /**
     * Get a file path from a Uri. This will get the the path for Storage Access
     * Framework Documents, as well as the _data field for the MediaStore and
     * other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri     The Uri to query.
     */
    public String getPathrimay(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public String getDataColumn(Context context, Uri uri, String selection,
                                String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }


}
